<template>
  <div class="test-md-wrapper">
    <div class="test-md-page">
      <header class="page-header">
        <div>
          <h1>测试数据渲染</h1>
          <p>
            来源：根目录 <code>test.md</code> 文件中全部 role = "assistant"
            的内容
          </p>
        </div>
        <div class="stats" v-if="assistantMessages.length">
          <span>对话数：{{ conversations.length }}</span>
          <span>助手回复：{{ assistantMessages.length }}</span>
        </div>
      </header>

      <el-alert
        v-if="errorMessage"
        type="error"
        :closable="false"
        :title="errorMessage"
        class="error-alert"
      />

      <section v-if="assistantMessages.length" class="message-list">
        <article
          v-for="msg in assistantMessages"
          :key="msg.id"
          class="message-card"
        >
          <header class="card-header">
            <div class="card-title">
              <el-icon><Document /></el-icon>
              <span>{{ msg.conversationTitle }}</span>
            </div>
            <span class="msg-index">#{{ msg.index }}</span>
          </header>
          <div class="card-content">
            <div class="render-block">
              <div class="render-title primary">markdown-it 渲染</div>
              <div
                class="render-body"
                v-html="renderMarkdown(msg.normalizedContent || msg.content)"
              ></div>
            </div>
            <div class="render-block alt">
              <div class="render-title">Showdown 渲染（实验一）</div>
              <div
                class="render-body"
                v-html="
                  renderMarkdownShowdown(msg.normalizedContent || msg.content)
                "
              ></div>
            </div>
            <div class="render-block alt second">
              <div class="render-title">remark 渲染（实验二）</div>
              <div
                class="render-body"
                v-html="
                  renderMarkdownRemark(msg.normalizedContent || msg.content)
                "
              ></div>
            </div>
          </div>
        </article>
      </section>

      <el-empty
        v-else-if="!errorMessage"
        description="未找到助手回复内容"
        class="empty-state"
      />
    </div>
  </div>
</template>

<script setup>
import { computed, ref, onMounted } from "vue";
import MarkdownIt from "markdown-it";
import showdown from "showdown";
import { remark } from "remark";
import remarkHtml from "remark-html";
import { Document } from "@element-plus/icons-vue";
import { getConversationList } from "@/api/conversation";

// markdown-it 渲染器（主解析器）
const mdParser = new MarkdownIt({
  html: true,
  linkify: true,
  breaks: true,
});

const escapeHtml = mdParser.utils?.escapeHtml || ((str) => str);

mdParser.renderer.rules.image = (tokens, idx) => {
  const token = tokens[idx];
  const src = token.attrGet("src") || "";
  const altText = token.children?.map((child) => child.content).join("") || "";
  const displayText = altText || src || "图片";
  return `<div class="image-placeholder">[图片已省略：${escapeHtml(
    displayText
  )}]</div>`;
};

const conversations = ref([]);
const errorMessage = ref("");

// Showdown 渲染器（实验一）
const showdownConverter = new showdown.Converter({
  noHeaderId: true,
  smartIndentationFix: true,
  simplifiedAutoLink: false,
  openLinksInNewWindow: false,
  strikethrough: true,
  literalMidWordUnderscores: true,
  tables: true,
  simpleLineBreaks: false,
});

// remark 渲染管线（实验二）
const remarkProcessor = remark().use(remarkHtml, { sanitize: false });

const normalizeMarkdownContent = (text = "") => {
  if (!text) return "";
  return text
    .replace(/\r\n/g, "\n")
    .replace(/\r/g, "\n")
    .replace(/\\n/g, "\n")
    .replace(/\*\*\s+/g, "**")
    .replace(/__\s+/g, "__")
    .replace(/(\*\*.+?\*\*)\n(?=#+)/g, "$1\n\n")
    .replace(/([^\n])\n(?=#+)/g, (_, char) => `${char}\n\n`)
    .replace(/^\s+(?=#+)/gm, "")
    .replace(/(^|\n)(-\s{2,})/g, (_, prefix) => `${prefix}- `);
};

const loadConversationsFromApi = async () => {
  try {
    errorMessage.value = "";
    const res = await getConversationList(1, 100);
    const data = res?.data ?? res ?? {};
    conversations.value = data.list ?? [];
  } catch (error) {
    console.error("从接口获取对话列表失败", error);
    errorMessage.value =
      error?.message || "获取对话列表失败，请稍后重试。";
  }
};

onMounted(() => {
  loadConversationsFromApi();
});

const assistantMessages = computed(() => {
  if (!conversations.value.length) return [];
  const result = [];
  conversations.value.forEach((conversation, convIndex) => {
    const messages = conversation?.messages ?? [];
    messages.forEach((message, msgIndex) => {
      if (
        message?.role === "assistant" &&
        typeof message.content === "string" &&
        message.content.trim()
      ) {
        const content = message.content;
        result.push({
          id: `${conversation.id || convIndex}-${msgIndex}`,
          conversationTitle: conversation.title || `对话 ${convIndex + 1}`,
          content: content.trim(),
          normalizedContent: normalizeMarkdownContent(content.trim()),
          index: msgIndex + 1,
        });
      }
    });
  });
  return result;
});

const renderMarkdown = (content) => mdParser.render(content || "");
const renderMarkdownShowdown = (content) =>
  showdownConverter.makeHtml(content || "");

const renderMarkdownRemark = (content) => {
  if (!content) return "";
  try {
    const file = remarkProcessor.processSync(content);
    return String(file.value || "");
  } catch (e) {
    console.error("remark 解析失败", e);
    return content;
  }
};
</script>

<style scoped>
.test-md-wrapper {
  width: 100%;
  height: 100vh;
  overflow-y: auto;
  background: #f4f6fb;
  padding: 16px 0 32px;
}

.test-md-page {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px 28px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  gap: 16px;
  padding: 16px 24px;
  border-radius: 12px;
  background: linear-gradient(135deg, #3b82f6 0%, #6366f1 100%);
  color: #fff;
}

.page-header h1 {
  margin: 0 0 8px;
  font-size: 24px;
}

.page-header p {
  margin: 0;
  font-size: 14px;
  opacity: 0.9;
}

.page-header code {
  background: rgba(0, 0, 0, 0.2);
  padding: 2px 6px;
  border-radius: 4px;
  color: #fff;
}

.stats {
  display: flex;
  flex-direction: column;
  gap: 6px;
  font-weight: 600;
  text-align: right;
}

.error-alert {
  margin: 20px 0;
}

.message-list {
  margin-top: 24px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message-card {
  background: #fff;
  border-radius: 16px;
  padding: 28px;
  box-shadow: 0 10px 30px rgba(15, 23, 42, 0.12);
  border: 1px solid rgba(99, 102, 241, 0.12);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 14px;
  border-bottom: 1px solid #eef2ff;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #1e1e1e;
}

.card-title .el-icon {
  color: #6366f1;
  font-size: 18px;
}

.msg-index {
  font-size: 12px;
  color: #94a3b8;
}

.card-content {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 18px;
}

.render-block {
  border-radius: 12px;
  border: 1px solid #e3e6f0;
  background: #f9fafc;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.render-block.alt {
  background: #fef8eb;
  border-color: #fde4a5;
}

.render-title {
  padding: 10px 14px;
  font-size: 13px;
  font-weight: 600;
  color: #4b5563;
  background: rgba(148, 163, 184, 0.12);
}

.render-title.primary {
  color: #1d4ed8;
  background: rgba(59, 130, 246, 0.2);
}

.render-block.alt .render-title {
  color: #92400e;
  background: rgba(251, 191, 36, 0.18);
}

.render-body {
  padding: 14px 16px;
  line-height: 1.8;
  color: #374151;
  max-height: 520px;
  overflow: auto;
  font-size: 15px;
}

.render-body :deep(h1),
.render-body :deep(h2),
.render-body :deep(h3),
.render-body :deep(h4) {
  margin: 18px 0 10px;
  color: #111827;
}

.render-body :deep(p) {
  margin: 10px 0;
}

.render-body :deep(ul),
.render-body :deep(ol) {
  margin: 10px 0 10px 22px;
}

.render-body :deep(code) {
  background: rgba(99, 102, 241, 0.12);
  padding: 3px 7px;
  border-radius: 4px;
}

.render-body :deep(pre) {
  background: #0f172a;
  color: #f8fafc;
  padding: 14px;
  border-radius: 8px;
  overflow-x: auto;
}

.render-body :deep(.image-placeholder) {
  margin: 14px 0;
  padding: 11px 13px;
  border-radius: 8px;
  background: rgba(99, 102, 241, 0.1);
  color: #4c51bf;
  font-size: 14px;
  font-style: italic;
}

.empty-state {
  margin-top: 48px;
}

@media (max-width: 768px) {
  .test-md-wrapper {
    padding: 12px 0 32px;
  }

  .test-md-page {
    padding: 14px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .stats {
    text-align: left;
  }

  .card-content {
    grid-template-columns: 1fr;
  }
}
</style>
